/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.execute.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.HttpUtils;
import com.icinfo.cloud.provider.punish.common.nonlitigation.service.impl.CaseNonLitigationExecuteRecordServiceImpl;
import com.icinfo.cloud.provider.punish.execute.dto.ExecuteFilesRecordDto;
import com.icinfo.cloud.provider.punish.execute.dto.FilePreviewAddressDto;
import com.icinfo.cloud.provider.punish.execute.mapper.ExecuteFilesRecordMapper;
import com.icinfo.cloud.provider.punish.execute.mapper.ExecuteMainInfoMapper;
import com.icinfo.cloud.provider.punish.execute.model.ExecuteFilesRecord;
import com.icinfo.cloud.provider.punish.execute.model.ExecuteMainInfo;
import com.icinfo.cloud.provider.punish.execute.service.IExecuteFilesRecordService;
import com.icinfo.cloud.provider.punish.execute.vo.ExecuteStageLinkRelateDocumentVo;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述: 案源材料记录表 execute_files_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年08月24日
 */
@Service
public class ExecuteFilesRecordServiceImpl extends MyBatisServiceSupport implements IExecuteFilesRecordService {

    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(ExecuteFilesRecordServiceImpl.class);

    @Value("${nonLitigation.url}")
    private String url;

    @Value("${nonLitigation.api.filesUrl}")
    private String filesUrl;
    @Resource
    private ExecuteFilesRecordMapper executeFilesRecordMapper;

    @Resource
    private CaseNonLitigationExecuteRecordServiceImpl caseNonLitigationExecuteRecordService;

    @Resource
    private ExecuteMainInfoMapper executeMainInfoMapper;

    @Override
    public List<ExecuteStageLinkRelateDocumentVo> selectExecuteFiles(String executeId) {
        return executeFilesRecordMapper.selectExecuteFiles(executeId);
    }
    @Override
    public List<ExecuteStageLinkRelateDocumentVo> selectRuleNumberFiles(String executeId) {
        return executeFilesRecordMapper.selectRuleNumberFiles(executeId);
    }

    @Override
    public List<ExecuteFilesRecordDto> getExecuteFilesList(String executeId) {
        ExecuteMainInfo executeMainInfoWhere = new ExecuteMainInfo();
        executeMainInfoWhere.setExecuteId(executeId);
        ExecuteMainInfo executeMainInfo = executeMainInfoMapper.selectOne(executeMainInfoWhere);
        Example example = new Example(ExecuteFilesRecord.class);
        example.createCriteria().andEqualTo("executeId", executeId);
        List<ExecuteFilesRecord> executeFilesRecords = executeFilesRecordMapper.selectByExample(example);
        List<ExecuteFilesRecordDto> resultList = new ArrayList<>();
        try {
            String token = caseNonLitigationExecuteRecordService.getBearerToken("");
            if (ObjectUtil.isEmpty(token)) {
                throw new BusinessException("获取法院方token失败");
            }
            if (ObjectUtil.isNotEmpty(executeFilesRecords)) {
                for (ExecuteFilesRecord executeFilesRecord : executeFilesRecords) {
                    Map<String, Object> paramMap = new HashMap<>(16);
                    paramMap.put("wwstbh", executeFilesRecord.getFileUrl());
                    paramMap.put("fydm", executeMainInfo.getCourtCode());
                    String result = HttpUtils.doHttpPostWithToken(url + filesUrl, "Bearer " + token, paramMap);
                    if (StringUtils.isNotBlank(result)) {
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        if (ObjectUtil.isNotEmpty(jsonObject.get("code"))) {
                            if (Constant.STRING_200.equals(jsonObject.getString("code"))) {
                                JSONObject data = (JSONObject) jsonObject.get("data");
                                if (ObjectUtil.isNotEmpty(data)) {
                                    executeFilesRecord.setFileUrl(data.getString("sfzxclpath"));
                                    ExecuteFilesRecordDto recordDto = new ExecuteFilesRecordDto();
                                    BeanUtils.copyProperties(executeFilesRecord, recordDto);
                                    resultList.add(recordDto);
                                }
                                logger.info("获取法院文件地址路径成功 Successfully,result:{}", jsonObject.toString());
                            } else {
                                logger.info("获取法院文件地址路径失败 Fail,result:{}", jsonObject.toString());
                            }
                        } else {
                            logger.info("获取法院文件地址路径失败 Fail ,result:{}", jsonObject.toString());
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("查询失败 Fail ,result:{}", e.getMessage());
        }
        return resultList;
    }

    @Override
    public String getFilePreviewAddress(FilePreviewAddressDto filePreviewAddressDto) {
        try {
            String token = caseNonLitigationExecuteRecordService.getBearerToken("");
            if (ObjectUtil.isEmpty(token)) {
                throw new BusinessException("获取法院方token失败");
            }
            Map<String, Object> paramMap = new HashMap<>(16);
            paramMap.put("wwstbh", filePreviewAddressDto.getFileUrl());
            paramMap.put("fydm", filePreviewAddressDto.getCourtCode());
            String result = HttpUtils.doHttpPostWithToken(url + filesUrl, "Bearer " + token, paramMap);
            if (StringUtils.isNotBlank(result)) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                if (ObjectUtil.isNotEmpty(jsonObject.get("code"))) {
                    if (Constant.STRING_200.equals(jsonObject.getString("code"))) {
                        JSONObject data = (JSONObject) jsonObject.get("data");
                        if (ObjectUtil.isNotEmpty(data)) {
                            return data.getString("wwfilepath");
                        }
                        logger.info("获取法院文件地址路径成功 Successfully,result:{}", jsonObject.toString());
                    } else {
                        logger.info("获取法院文件地址路径失败 Fail,result:{}", jsonObject.toString());
                    }
                } else {
                    logger.info("获取法院文件地址路径失败 Fail ,result:{}", jsonObject.toString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("查询失败 Fail ,result:{}", e.getMessage());
        }
        return null;
    }
}